package com.qwz.learn;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 组合对象，通常需要存储子对象，定义有子部件的部件行为并实现在component里面定义的与子部件有关的操作
 * @Package: com.qwz.learn.Composite
 * @Author: Qiuwuzhi
 * @CreateDate: 2019/12/20  下午 9:23
 * @Version V1.0
 */
public class Composite extends Component {
    /**
     * 用来存储对象中包含的子组件对象
     */
    private List<Component> childComponents = null;

    /**
     * 示意方法，通常在里面需要实现递归调用
     */
    public void someOperation() {
        if (childComponents != null) {
            for (Component c : childComponents) {
                //递归地进行组件相应方法的调用
                c.someOperation();
            }
        }
    }

    @Override
    public void addChild(Component child) {
        if (childComponents == null) {
            childComponents = new ArrayList<Component>();
        }
        childComponents.add(child);
    }

    @Override
    public void removeChild(Component child) {
        if (childComponents != null) {
            childComponents.remove(child);
        }
    }

    @Override
    public Component getChild(int index) {
        if (childComponents != null) {
            if (index >= 0 && index < childComponents.size()){
                return childComponents.get(index);
            }
        }
        return  null;
    }
}
